import { reactive, ref, onMounted } from 'vue'
import captcha from '@/services/captcha/index'
import { ElNotification } from 'element-plus'
import { encryptByDES } from '@/utils/utils'
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';

export function useLoginFunc() {

    const router = useRouter() // 组件内路由
    const route = useRoute() // 组件内路由信息
    const store = useStore()

    // 表单验证
    const form = reactive({
        username: "yykk",
        password: "123456",
        code: "",
        uuid: "",
    })

    // 用对象装验证码的数据
    const captchaObj = reactive({
        img: "",
        token: ""
    })

    // 定义属性
    var loading = ref(false);

    // 表单验证
    const formRef = ref(null);
    // 1: 初始化验证码
    const initCaptcha = () => {
        // 获取服务器的验证码信息
        var promise = captcha();
        // 处理服务器返回的验证码数据信息
        promise.then(res => {
            // 接受服务器返回的验证码信息
            captchaObj.img = res.data.data.img;
            captchaObj.token = res.data.data.token;
            // 接受缓存的key,在登录的时候用于获取缓存的验证码
            form.uuid = res.data.data.token;
        })
    };

    const changecode = () => {
        initCaptcha();
    }

    onMounted(() => {
        initCaptcha()
    })

    // 表单验证规则
    const rules = {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
    };

    // 表单提交
    const onSubmit = () => {
        // 提交验证
        formRef.value.validate((valid) => {
            if (!valid) { return false; }

            loading.value = true
            form.password = encryptByDES(form.password)
                // 调用状态管理的方法dispatch这里掉actions commit是调用mutations方法
            var promise = store.dispatch("login/logined", form);
            promise.then((res) => {
                ElNotification({ message: "登录成功", duration: 3000, type: "success" })
                const params = route.query.redirect;
                router.push(params || "/");
            }, err => {
                ElNotification({ message: err.msg, duration: 3000, type: "error" })
                if (err.status == '101100605') {
                    form.code = "";
                }
            }).finally(() => {
                loading.value = false;
            });
        });
    }

    return {
        form,
        changecode,
        onSubmit,
        rules,
        captchaObj,
        formRef,
        loading
    }
}